package com.shiwaixiangcun.customer.module.houserenting

import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.support.v7.widget.GridLayoutManager
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import com.google.gson.reflect.TypeToken
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.Response
import com.shiwaixiangcun.customer.ConfigSps
import com.shiwaixiangcun.customer.GlobalApi
import com.shiwaixiangcun.customer.R
import com.shiwaixiangcun.customer.app.App
import com.shiwaixiangcun.customer.base.BaseActivity
import com.shiwaixiangcun.customer.event.EventUtil
import com.shiwaixiangcun.customer.event.SimpleEvent
import com.shiwaixiangcun.customer.glide.BannerImageLoader
import com.shiwaixiangcun.customer.interfaces.RequestPermissionType
import com.shiwaixiangcun.customer.network.ResponseConfig
import com.shiwaixiangcun.customer.ui.dialog.DialogLoginOut
import com.shiwaixiangcun.customer.utils.AppSharePreferenceMgr
import com.shiwaixiangcun.customer.utils.HouseAttrUtil
import com.shiwaixiangcun.customer.utils.JsonUtil
import kotlinx.android.synthetic.main.activity_house_detail.*
import kotlinx.android.synthetic.main.top_bar_transparent.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.HashMap
import kotlin.collections.ArrayList
import kotlin.collections.MutableList
import kotlin.collections.map
import kotlin.collections.set


/***
 * 房屋租售  房屋详情页面
 */

class HouseDetailActivity : BaseActivity(), View.OnClickListener {

    companion object {
        const val REQUEST_DATA = 0x1001
    }

    var id: Long? = null
    var type: String? = null
    private var mAdapterSurvey: AdapterSurvey? = null
    private var mSurveyList: MutableList<HouseDescription>? = null

    private var agentNumber: String? = null
    private var phoneNumber: String? = null
    override fun onClick(p0: View?) {

        when (p0?.id) {
            R.id.back_left -> {
                finish()
            }
            R.id.btn_submit -> {
                showDialog(agentNumber)
            }
        }
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_house_detail)
        scrollview.scrollTo(0, 0)
        EventUtil.getInstance().register(this)
        initBundleData()
        initViewAndEvent()
        initData()
    }

    private fun initViewAndEvent() {

        tv_page_name.text = "房屋详情"
        back_left.setOnClickListener(this)
        btn_submit.setOnClickListener(this)


        val detailUrl = "${GlobalApi.houseDetail}$id/view.htm"

        val siteId = AppSharePreferenceMgr.get(App.getContext(), ConfigSps.CURRENT_SITE_ID, 20) as Int
        val header = HashMap<String, String>(2)

        header["siteId"] = "" + siteId
        webview_house.loadUrl(detailUrl, header)


    }



    override fun onDestroy() {
        if (webview_house != null) {
            webview_house.loadDataWithBaseURL(null, "", "text/html", "utf-8", null)
            webview_house.clearHistory()

            (webview_house.parent as ViewGroup).removeView(webview_house)
            webview_house.destroy()

        }
        EventUtil.getInstance().unregister(this)
        super.onDestroy()
    }


    /**
     * 获取房屋详细数据
     */
    private fun initData() {

        val url = "${GlobalApi.houseDetail}$id.json"
        OkGo.get<String>(url)
                .execute(object : StringCallback() {
                    override fun onSuccess(response: Response<String>?) {
                        val type = object : TypeToken<CommonDataEntity<HouseDetailEntity>>() {}.type
                        val detailData = JsonUtil.fromJson<CommonDataEntity<HouseDetailEntity>>(response?.body(), type)
                        when (detailData.responseCode) {
                            ResponseConfig.SUCCESS -> {
                                EventUtil.getInstance().post(SimpleEvent(SimpleEvent.HOUSE_DETAIL, REQUEST_DATA, detailData.data))
                            }
                        }
                    }
                })

    }

    private fun initBundleData() {
        id = intent.extras.getLong("houseId")
        type = intent.extras.getString("type")


    }

    @SuppressLint("SetTextI18n")
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun updateUI(simpleEvent: SimpleEvent) {

        if (simpleEvent.mEventType != SimpleEvent.HOUSE_DETAIL) {
            return
        }
        when (simpleEvent.mEventValue) {
            REQUEST_DATA -> {
                scrollview.scrollTo(0, 0)
                val data: HouseDetailEntity = simpleEvent.data as HouseDetailEntity
                val imageList = data.images.map { it.thumbImageURL }


                when (type) {
                    "rentHouse" -> {
                        tv_pay_name.text = "租金"
                        tv_price_desc.text = "元/月"
                        layout_house_config.visibility = View.VISIBLE
                    }
                    "saleHouse" -> {
                        tv_pay_name.text = "售价"
                        tv_price_desc.text = "万"
                        layout_house_config.visibility = View.GONE
                    }
                }

                //agentInfo
                agentNumber = data.agentPhone
                //banner
                if (imageList.isEmpty()) {
                    banner_house.visibility = View.GONE
                } else {
                    banner_house.visibility = View.VISIBLE

                    banner_house.setImages(imageList)
                            .setImageLoader(BannerImageLoader())
                            .setDelayTime(4000)
                            .start()

                }


                //房屋信息
                tv_house_title.text = data.name
                tv_house_type.text = data.structureName
                tv_house_size.text = "${data.buildingArea}平方米"
                tv_house_price.text = data.price



                if (data.payName == null) {
                    tv_pay_way.visibility = View.INVISIBLE
                } else {
                    tv_pay_way.text = data.payName
                    //房源概况

                }
                mSurveyList = ArrayList()
                mAdapterSurvey = AdapterSurvey(mSurveyList)
                mSurveyList?.addAll(data.houseDescriptions)
                mAdapterSurvey?.notifyDataSetChanged()



                rv_survey.layoutManager = GridLayoutManager(mContext, 2)
                rv_survey.adapter = mAdapterSurvey
                mAdapterSurvey?.notifyDataSetChanged()


                //其他配置


                if (data.configs.isEmpty() || data.configs == null) {
                    layout_house_config.visibility = View.GONE
                } else {
                    val split = data.configs.split(delimiters = "、")
                    val list = split.map {
                        AttrEntity(it, HouseAttrUtil.get(it))
                    }
                    val attrsAdapter = AttrsAdapter(list)

                    rv_attr.layoutManager = GridLayoutManager(mContext, 4)
                    rv_attr.adapter = attrsAdapter
                    attrsAdapter.notifyDataSetChanged()
                }

                //其他描述


            }
        }
    }


    private fun showDialog(phone: String?) {
        val dialogLoginOut = DialogLoginOut(mContext, R.layout.item_dialog_call_phone)
        dialogLoginOut.setTitle("是否要拨打此电话？")
        dialogLoginOut.setMessage(phone)
        dialogLoginOut.setYesOnclickListener("是", DialogLoginOut.OnPositiveOnclickListener {
            dialogLoginOut.dismiss()
            requestPermission(phone)
        })

        dialogLoginOut.setNoOnclickListener("否") { dialogLoginOut.dismiss() }
        dialogLoginOut.show()
    }

    private fun requestPermission(number: String?) {
        //判断Android版本是否大于23
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val checkCallPhonePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE)

            if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.CALL_PHONE),
                        RequestPermissionType.REQUEST_CODE_ASK_CALL_PHONE)
                return
            } else {
                callPhone(number)
            }
        } else {
            callPhone(number)
        }
    }


    /**
     * 注册权限申请回调
     * @param requestCode 申请码
     * @param permissions 申请的权限
     * @param grantResults 结果
     */
    @Override
    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
        when (requestCode) {
            RequestPermissionType.REQUEST_CODE_ASK_CALL_PHONE -> if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                callPhone(agentNumber)
            } else {
                // Permission Denied
                Toast.makeText(this, "CALL_PHONE Denied", Toast.LENGTH_SHORT).show()
            }
            else -> super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        }
    }

    /**
     * 拨号方法
     */
    @SuppressLint("MissingPermission")
    private fun callPhone(number: String?) {
        val intent = Intent(Intent.ACTION_CALL, Uri.parse("tel:" + number))
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        startActivity(intent)
    }
}
